package finedev.work.vennue;

import java.io.IOException;
import java.util.HashMap;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class JoinActivity extends Activity {
	
	private Activity mActivity = null;
	
	private Button btnGenreSelect = null;
	private Button btnJoin = null;
	
	private String mSelectedGenre;
	
	protected CharSequence[] _options = { "락", "발라드", "째즈", "댄스", "어쿠스틱", "하우스/일렉" };
	protected String[] _optionsValue = {"Rock", "Ballad", "Jazz", "Dance", "Acoustic", "House" };
	protected boolean[] _selections =  new boolean[ _options.length ];
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_join);
        
        mActivity = this;
        
        btnGenreSelect = (Button) findViewById( R.id.join_btn_genreselect );
        btnGenreSelect.setOnClickListener( onClickListener );
        
        btnJoin = (Button) findViewById( R.id.join_btn_join );
        btnJoin.setOnClickListener( onClickListener );
    }
    
    private View.OnClickListener onClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if ( v.getId() == R.id.join_btn_genreselect ) {
				showDialog( 0 );
			} else if ( v.getId() == R.id.join_btn_join ) {
				ProgressDialog progressDialog = new ProgressDialog( mActivity );
				progressDialog.setMessage("join...");
				progressDialog.setCancelable(false);
				
				JoinManager joinManager = new JoinManager( (JoinActivity) mActivity, progressDialog);
				
//				$user_id = $_POST['reg_id'];
//				$email=$_POST['reg_email'];
//				$name=$_POST['reg_name'];
//				$passwd=$_POST['reg_passwd'];
//				$passwd2=$_POST['reg_passwd2'];
//				$genre=implode(',', $_POST['genre']);
				
//				joinManager.execute( "http://www.vennue.net/new/m_register.php", 
//						((EditText) findViewById(R.id.join_edittext_id)).getText().toString(),
//						((EditText) findViewById(R.id.join_edittext_email)).getText().toString(),
//						((EditText) findViewById(R.id.join_edittext_name)).getText().toString(),
//						((EditText) findViewById(R.id.join_edittext_password)).getText().toString(),
//						((EditText) findViewById(R.id.join_edittext_passwordrepeat)).getText().toString(),
//						 mSelectedGenre );
				
				joinManager.execute( "http://www.vennue.net/new/m_register.php", 
						String.valueOf("TestId1"),
						String.valueOf("test@test.co.kr"),
						String.valueOf("주람테스트"),
						String.valueOf("123455"),
						String.valueOf("123455"),
						 "dance,jazz" );
				
//				joinManager.execute( "http://www.vennue.net/new/m_register.php", 
//						 String.valueOf("copper34"),
//						 String.valueOf("woong2star") );
				
				Log.i("LoginActivity", "loginManager execute" );
			}
		}
	};
	
	private void JoinSuccess()
	{
//		Toast.makeText( mActivity, "회원가입 성공",
//                Toast.LENGTH_SHORT).show();
		makeShortToast("회원가입 성공");
		
		finish();
	}
	
	private void makeShortToast(String text)
	{
		Toast.makeText( mActivity, text,
                Toast.LENGTH_SHORT).show();
	}
	
	private void JoinFail(int errorCode ){
		switch( errorCode ){
		case 2:
			makeShortToast("DB에러 입니다.");
			break;
		case 3:
			makeShortToast("아이디 중복 입니다.");
			break;
		case 4:
			makeShortToast("모두 작성해주세요.");
			break;
		case 5:
			makeShortToast("비밀번호가 확인과 일치하지 않습니다.");
			break;
		case 6:
			makeShortToast("비밀번호가 6~16자리가 아닙니다.");
			break;
		}
		
		return;
	}
	
	protected void ReceiveSuccess(String responseStr) throws JsonParseException, JsonMappingException, IOException
    {
    	JoinManager.mHashMapResult = new ObjectMapper().readValue( responseStr, HashMap.class );
		Log.i("Join", JoinManager.mHashMapResult.toString() );  
		
		if ( Integer.parseInt( String.valueOf( JoinManager.mHashMapResult.get("result")) ) == 1 ) {
//		if ( Integer.parseInt((JoinManager.mHashMapResult.get("result")) == 1) {
			JoinSuccess();
		} else {
			JoinFail( Integer.parseInt( String.valueOf( JoinManager.mHashMapResult.get("result")) ) );
		}
    }
    protected void ReceiveFail(String errorMessage)
    {
    	
    }
	
	protected android.app.Dialog onCreateDialog(int id) {
		
		switch( id ) {
		
		case 0:
			
			return new AlertDialog.Builder( mActivity )
				.setTitle( getString(R.string.genreselect_kor) )
				.setMultiChoiceItems( _options, _selections, new DialogInterface.OnMultiChoiceClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which, boolean isChecked) {
						// TODO Auto-generated method stub
						
					}
				})
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						setChoiceCountInView();
					}
				})
				.setNegativeButton("cancel", null )
				.create();
			
		}
		
		return null;
		
	};
	
	protected void setChoiceCountInView() 
	{
		int count = 0;
		mSelectedGenre = "";
		for (int i = 0; i < _options.length; i++) {
			if ( _selections[i] ) {
				if ( mSelectedGenre == "" ){ 
					mSelectedGenre += _optionsValue[i];
				} else {
					mSelectedGenre += "," + _optionsValue[i];
				}
				count++;
			}
		}
		btnGenreSelect.setText("장르 선택하기 ( " + count + "개 선택됨 )");
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_join, menu);
        return true;
    }
}
